import React, { useState } from 'react';
import { useLocation } from 'react-router-dom';

import App from './app';

interface CSSTransitionProps extends React.HTMLAttributes<HTMLDivElement> {
    ignoreTransitionIf?: (locationPathName, displayLocationPathName) => boolean;
}

const CSSTransition: React.FC<CSSTransitionProps> = (props) => {
    const { children, ignoreTransitionIf, ...restProps } = props;
    const location = useLocation();

    const [displayLocation, setDisplayLocation] = useState(location);
    const [transitionStage, setTransistionStage] = useState('fadeIn');

    // Global event
    const triggerRouteChange = () => {
        setDisplayLocation(location);
        App.trigger('route:change', location.pathname);
    };

    // route change request => Fade Out => Fade In => route change
    // route change request => route change

    React.useEffect(() => {
        // console.log(location.pathname, displayLocation.pathname);
        if (
            location.pathname !== displayLocation.pathname
            // Uncomment to limit the transition between home and general page.
        ) {
            if (ignoreTransitionIf && ignoreTransitionIf(location.pathname, displayLocation.pathname)) {
                // console.log('trigger');
                // triggerRouteChange();
            } else {
                setTransistionStage('fadeOut');
            }
        }
    }, [location, displayLocation]);

    return (
        <div
            className={`${transitionStage}`}
            onAnimationEnd={() => {
                if (transitionStage === 'fadeOut') {
                    setTransistionStage('fadeIn');
                    // Trigger route change after animation is done.
                    triggerRouteChange();
                }
            }}
            {...restProps}
        >
            {children}
        </div>
    );
};

export default CSSTransition;
